<?php

namespace mpend\modules\commission\controllers;

use Yii;
use mpend\components\Controller;
use yii\imagine\Image;
use Imagine\Image\ManipulatorInterface;
use common\helpers\Utils;
use yii\web\Response;

/**
 * ExtendController
 *
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class ExtendController extends Controller {

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex() {
        return $this->render('index');
    }

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionPoster() {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $member = $this->module->member;
        $ticket = null;
        $qrcode = null;
        $root = Yii::getAlias('@uploads');
        $savefile = null;
        if ($member !== null) {
            $path = '/member/';
            Utils::dirCreate($root . $path);
            $filename = $member->id . '.jpg';
            $savefile = $path . $filename;
            if (file_exists($root . $savefile)) {
                return [
                    'status' => true,
                    'url' => Utils::cdn($savefile),
                ];
            }
            $qrcode = $member->qrcode?:'@webroot/images/qrcode/' . Yii::$app->params['wechat']['original_id'] . '.jpg';
            $bg = parent::getSiteConfigs('commission-spread-background', '@webroot/images/qrcode_bg.jpg');

            list($width, $height) = getimagesize(Yii::getAlias($bg));
            list($qrcode_width, $qrcode_height) = getimagesize($qrcode);

            $px = $width / 2 - $qrcode_width / 2;
            $py = $height - $qrcode_height - 80;

            Image::watermark($bg, $qrcode, [$px, $py])->save($root . $savefile);
        }

        if ($savefile) {
            return [
                'status' => true,
                'url' => Utils::cdn($savefile),
            ];
        }
        return [
            'status' => false,
            'msg' => '获取失败，请刷新再试',
        ];
    }

}
